﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using FinalPointSet.Model.Asset;
using FinalPointSet.Model.Constant;
using FinalPointSet.Model.Constant.Message;
using FinalPointSet.Model.Constants;
using FinalPointSet.Model.Manager;
using ICSharpCode.AvalonEdit.Highlighting;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows;
using static FinalPointSet.Model.Manager.MessageManager;

namespace FinalPointSet.ViewModel.Page.MainView
{
    public partial class DependencyPageViewModel : ObservableObject
    {
        /// <summary>
        /// 输入的SQL
        /// </summary>
        [ObservableProperty]
        private string _SourceSQL = String.Empty;
        /// <summary>
        /// 解析后的结果, 表的依赖
        /// </summary>
        [ObservableProperty]
        private string _TableDependency = String.Empty;
        /// <summary>
        /// 高亮样式
        /// </summary>
        [ObservableProperty]
        private IHighlightingDefinition? _highlightingDefinition;
        /// <summary>
        /// 复制按钮可见性
        /// </summary>
        [ObservableProperty]
        private Visibility _CopyButtonVisibility = Visibility.Hidden;
        public DependencyPageViewModel()
        {
            //设置高亮
            //设置代码高亮
            ObjectPair<IHighlightingDefinition>? hightLightDef = AssetManager.Instance.GetObjectListElementByKey<IHighlightingDefinition>(Path.HighLightDefinition, "SQL");
            if (hightLightDef != null)
            {
                HighlightingDefinition = hightLightDef.Value;
            }
        }

        /// <summary>
        /// 解析依赖
        /// </summary>
        [RelayCommand]
        private void Transform()
        {
            //剔除右括号、分号
            string firstETLInput = SourceSQL.ToLower().Replace(")", " ").Replace(";", " ") + " "; //追加一个空格,防止SQL最后无法判定结尾
            //将多个空格、换行符、制表符，替换为1个空格
            string ETLInput = Regex.Replace(firstETLInput, @"\s+", " ");
            Debug.Print($"DependencyPageViewModel.Transform(), {ETLInput}");
            const string symbol_from = "from ";
            const string symbol_join = "join ";

            try
            {
                //解析SQL中的依赖
                List<string> dependencies_from = ParseDependency(ETLInput, symbol_from);
                List<string> dependencies_join = ParseDependency(ETLInput, symbol_join);
                List<string> dependencies_total = dependencies_from.Union(dependencies_join).Distinct().ToList();
                List<string> filteredDependencies = dependencies_total.Where(t => t.Contains('.')).ToList();
                filteredDependencies.Sort();
                //格式化返回结果
                string result = string.Join("\n", filteredDependencies);
                if (filteredDependencies.Count == 0)
                {
                    TableDependency = string.Empty;
                    Broadcast(MsgType.GrowMsg, new GrowMsgArg(WindowType.MainView, GrowlMsgType.Warning, $"输入待识别的SQL为空或不规范, 请重新输入!"));
                }
                else
                {
                    TableDependency = result;
                }
            }
            catch (Exception e)
            {
                Broadcast(MsgType.GrowMsg, new GrowMsgArg(WindowType.MainView, GrowlMsgType.Error, $"依赖识别失败! 错误原因:{e.Message}"));
                return;
            }

            try
            {
                if (string.IsNullOrEmpty(TableDependency))
                    return;

                Copy();
                CopyButtonVisibility = Visibility.Visible;
            }
            catch (Exception e)
            {
                Debug.Print($"DependencyPageViewModel.Transform(), 复制文本到剪贴板失败!,失败原因:{e.Message}");
            }
        }

        /// <summary>
        /// 重置输入输出
        /// </summary>
        [RelayCommand]
        private void Reset()
        {
            SourceSQL = String.Empty;
            TableDependency = String.Empty;
            CopyButtonVisibility = Visibility.Hidden;
        }

        /// <summary>
        /// 复制结果到剪贴板
        /// </summary>
        [RelayCommand]
        private void Copy()
        {
            if (!string.IsNullOrEmpty(TableDependency))
            {
                Clipboard.SetText(TableDependency);
                Broadcast(MsgType.GrowMsg, new GrowMsgArg(WindowType.MainView, GrowlMsgType.Success, $"识别成功, 结果已复制到剪贴板"));
            }
        }

        /// <summary>
        /// 解析SQL的依赖
        /// </summary>
        /// <param name="targetStr">SQL字符串</param>
        /// <param name="symbol">标识</param>
        /// <returns></returns>
        private static List<string> ParseDependency(string targetStr, string symbol)
        {
            List<string> dependencies = [];
            int length = symbol.Length;
            //循环提取"from "关键词存在的位置
            int index = targetStr.IndexOf(symbol, 0);
            while (index != -1)
            {
                //截取from之后的字符串
                int startIndex = index + length;
                String curString = targetStr.Substring(startIndex, targetStr.Length - startIndex);
                Debug.Print(curString);
                //找到第一个空格，即为依赖的表字符串
                int spaceIndex = curString.IndexOf(" ");
                String matchString = curString.Substring(0, spaceIndex);
                Debug.Print(matchString);
                dependencies.Add(matchString);
                //更新截取索引
                startIndex += spaceIndex;
                index = targetStr.IndexOf(symbol, startIndex);
            }
            return dependencies;
        }
    }
}
